<template>
  <div style="display: flex">
    <div class="tab" v-if="false">
      <div
        class="tab-item"
        :class="{ active: tabActive == 'Map' }"
        @click="tabActive = 'Map'"
      >
        Map
      </div>
      <div
        class="tab-item"
        :class="{ active: tabActive == 'Diagram' }"
        @click="tabActive = 'Diagram'"
      >
        Diagram
      </div>
    </div>
    <div id="cesium-container" v-show="tabActive == 'Map'"></div>
    <div class="legend">
      <div class="legend-item">
        <div
          class="legend-icon"
          style="background-color: rgb(191, 0, 255)"
        ></div>
        <div>P4</div>
      </div>
      <div class="legend-item">
        <div
          class="legend-icon"
          style="background-color: rgb(0, 255, 255)"
        ></div>
        <div>P5</div>
      </div>
      <div class="legend-item">
        <div class="legend-icon" style="background-color: rgb(255, 0, 0)"></div>
        <div>P6</div>
      </div>
      <!-- <div class="legend-item">
        <div
          class="legend-icon"
          style="background-color: rgb(132, 211, 127)"
        ></div>
        <div>P6.2</div>
      </div> -->
      <div class="legend-item">
        <div
          class="legend-icon"
          style="background-color: rgb(255, 165, 0)"
        ></div>
        <div>P7</div>
      </div>
      <div class="legend-item">
        <div class="legend-icon" style="background-color: rgb(0, 255, 0)"></div>
        <div>P8</div>
      </div>
      <div class="legend-item">
        <div
          class="legend-icon"
          style="background-color: rgb(167, 89, 9)"
        ></div>
        <div>其他</div>
      </div>
    </div>
    <div v-show="tabActive == 'Diagram'"></div>
    <div class="left-side" v-show="expand && false">
      <div class="tab">
        <div
          class="tab-item"
          :class="{ active: subTabActive == 'RWPS' }"
          @click="subTabActive = 'RWPS'"
        >
          RWPS
        </div>
        <div
          class="tab-item"
          :class="{ active: subTabActive == 'WTW' }"
          @click="subTabActive = 'WTW'"
        >
          WTW
        </div>
        <div
          class="tab-item"
          :class="{ active: subTabActive == 'Res.' }"
          @click="subTabActive = 'Res.'"
        >
          Res.
        </div>
      </div>
      <div class="content" v-show="subTabActive == 'RWPS'">
        <div class="content-item">
          <div class="title">
            <div class="info">Muk Wu No.3</div>
          </div>
          <div class="table">
            <div class="table-header">
              <div>Delivery to</div>
              <div>Water Pumped (ML/h)</div>
              <div>Pressure (M)</div>
            </div>
            <div class="table-body">
              <div>Sheung Shui WTW & Fanling RWPS</div>
              <div>11.28</div>
              <div>40.02</div>
            </div>
            <div class="table-body">
              <div>Sheung Shui WTW & Fanling RWPS</div>
              <div>11.28</div>
              <div>40.02</div>
            </div>
          </div>
        </div>
        <div class="content-item">
          <div class="title">
            <div class="info">Muk Wu No.3</div>
          </div>
          <div class="table">
            <div class="table-header">
              <div>Delivery to</div>
              <div>Water Pumped (ML/h)</div>
              <div>Pressure (M)</div>
            </div>
            <div class="table-body">
              <div>Sheung Shui WTW & Fanling RWPS</div>
              <div>11.28</div>
              <div>40.02</div>
            </div>
            <div class="table-body">
              <div>Sheung Shui WTW & Fanling RWPS</div>
              <div>11.28</div>
              <div>40.02</div>
            </div>
          </div>
        </div>
      </div>
      <div class="content" v-show="subTabActive != 'RWPS'">
        <div class="content-item">
          <div class="title">
            <div class="info">Au Tau</div>
          </div>
          <div class="table">
            <div
              class="table-body"
              style="justify-content: space-between; padding: 0 10px"
            >
              <div>Water Yield (ML/h)</div>
              <div style="justify-content: flex-end">6.7</div>
            </div>
          </div>
        </div>
        <div class="content-item">
          <div class="title">
            <div class="info">Au Tau</div>
          </div>
          <div class="table">
            <div
              class="table-body"
              style="justify-content: space-between; padding: 0 10px"
            >
              <div>Water Yield (ML/h)</div>
              <div style="justify-content: flex-end">6.7</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="arrow" v-if="false">
      <div
        class="arrow-left arrow-item"
        v-show="expand"
        @click="expand = false"
      >
        &lt;
      </div>
      <div
        class="arrow-right arrow-item"
        v-show="!expand"
        @click="expand = true"
      >
        &gt;
      </div>
    </div>
    <div class="right-side" v-if="false">
      <div class="component">
        <div class="component-item">{{ date }}</div>
        <div class="component-item"></div>
      </div>
      <div class="content-item">
        <div class="title">
          <div class="info">DJ water import amount</div>
          <div class="select" style="width: 50px">
            <el-select v-model="DJValue" size="small">
              <el-option
                v-for="item in DJOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>
      <div class="content-item">
        <div class="title">
          <div class="info">RWPS Consumption & Efficiency</div>
          <div class="select" style="width: 80px">
            <el-select v-model="RWPSValue" size="small">
              <el-option
                v-for="item in RWPSOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>
      <div class="content-item">
        <div class="title">
          <div class="info">Pumps Operation & Priority</div>
          <div class="select" style="width: 80px">
            <el-select v-model="PumpsValue" size="small">
              <el-option
                v-for="item in PumpsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>
    </div>
    <div class="pump-btn" @click="flyTo(pump)">大浦咸水泵站</div>
    <div class="pump-btn" @click="flyTo(pump2)" style="right: 180px">
      木湖原水泵站
    </div>
  </div>
</template>

<script name="Index" setup>
import * as Cesium from "cesium";
import { ref, computed, onMounted, reactive } from "vue";
import {
  handleFromDegreesArray,
  getDistance,
  handleFromDegreesArrayHeight,
  formatDateByProp,
  tranformCoordinate,
} from "@/utils/map";
import mapData from "@/assets/map/R_MAIN.json";
import heightData from "@/assets/map/heightData.js";
import airValveData from "@/assets/map/R_AIRVALVE.json";
import airValveHeight from "@/assets/map/airValveHeight.js";
import flowctlValveData from "@/assets/map/R_FLOWCTLVALVE.json";
import flowctlValveHeight from "@/assets/map/flowctlValveHeight.js";
import arrow_img from "@/assets/images/arrow.png";
import surface_img from "@/assets/images/surface.jpg";

Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2ZTgxOGNhZC03NThmLTQ0NzMtOTNlYS1kNmM3YzlmZDU3NTMiLCJpZCI6MTI1NTY3LCJpYXQiOjE2NzY5MDI0MzJ9.ulIEz3NCh2cMEBiHrqIuv9I6icn5KTMMnBdy2wassoM";

let viewer;
let pump;
let pump2;
let dateInterval;
const volume_animation = {};
const volume_animation_primitives = {};
let zoom = 1;

const date = ref(null);
const tabActive = ref("Map");
const subTabActive = ref("RWPS");
const expand = ref(true);
const DJValue = ref(undefined);
const DJOptions = ref([
  {
    value: "daily",
    label: "日",
  },
  {
    value: "monthly",
    label: "月",
  },
  {
    value: "annually",
    label: "年",
  },
]);
const RWPSValue = ref(undefined);
const RWPSOptions = ref([
  {
    value: "2023-06-05",
    label: "2023-06-05",
  },
  {
    value: "2023-07-05",
    label: "2023-07-05",
  },
]);
const PumpsValue = ref(undefined);
const PumpsOptions = ref([
  {
    value: "Muk Wu No.2",
    label: "Muk Wu No.2",
  },
  {
    value: "Muk Wu No.3",
    label: "Muk Wu No.3",
  },
]);

const start = Cesium.JulianDate.fromDate(new Date());

// 添加地图
const initMap = () => {
  viewer = new Cesium.Viewer("cesium-container", {
    infoBox: false, // 信息框
    timeline: false, // 时间轴小部件
    homeButton: false, // 定位到地球视角按钮
    baseLayerPicker: false, // 选择底图按钮
    navigationHelpButton: false, // 帮助按钮
    animation: false, // 动画小部件
    sceneModePicker: false, // 切换2D/3D按钮
    fullscreenButton: false, // 全屏按钮
    terrainProvider: Cesium.createWorldTerrain(), // 生成地形
    requestRenderMode: true,
    maximumRenderTimeChange: Infinity,
  });
  // 去掉logo
  viewer.cesiumWidget.creditContainer.style.display = "none";
  viewer.scene.globe.depthTestAgainstTerrain = true;

  // 亮度设置
  viewer.scene.light = new Cesium.DirectionalLight({
    direction: viewer.scene.camera.directionWC,
  });
  viewer.scene.preRender.addEventListener(function (scene, time) {
    viewer.scene.light.direction = Cesium.Cartesian3.clone(
      viewer.scene.camera.directionWC,
      viewer.scene.light.direction
    );
  });
  var stages = viewer.scene.postProcessStages;
  viewer.scene.brightness =
    viewer.scene.brightness ||
    stages.add(Cesium.PostProcessStageLibrary.createBrightnessStage());
  viewer.scene.brightness.enabled = true;
  viewer.scene.brightness.uniforms.brightness = Number(1);

  // 适度降低分辨率
  viewer._cesiumWidget._supportsImageRenderingPixelated =
    Cesium.FeatureDetection.supportsImageRenderingPixelated();
  viewer._cesiumWidget._forceResize = true;
  if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
    var vtxf_dpr = window.devicePixelRatio;
    while (vtxf_dpr >= 2.0) {
      vtxf_dpr /= 2.0;
    }
    viewer.resolutionScale = vtxf_dpr;
  }
  // 是否开启抗锯齿
  if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
    // 判断是否支持图像渲染像素化处理
    viewer.resolutionScale = window.devicePixelRatio;
  }
};
// 添加点击事件
const addHandler = () => {
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  // 点击事件
  handler.setInputAction((click) => {
    // 返回一个ray和地球表面的一个交点的Cartesian3坐标。
    let ray = viewer.camera.getPickRay(click.position);
    let cartesian = viewer.scene.globe.pick(ray, viewer.scene);
    // // 空间坐标转世界坐标(弧度)
    let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
    // 弧度转为角度（经纬度）
    let lon = Cesium.Math.toDegrees(cartographic.longitude); //经度值
    let lat = Cesium.Math.toDegrees(cartographic.latitude); //纬度值
    // 地形高度(下面两个二选一就行)
    let height = cartographic.height;
    let height2 = viewer.scene.globe.getHeight(cartographic);
    console.log("经纬度高程是：", {
      x: lon,
      y: lat,
      height: height,
      height2: height2,
    });
    let pick = viewer.scene.pick(click.position);
    if (!pick) return;
    console.log("pick:", pick);
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  // 滚动事件
  return;
  handler.setInputAction((wheel) => {
    let height = viewer.camera.positionCartographic.height;
    if (height >= 100000) {
      if (zoom == 1) return;
      zoom = 1;
      console.log(zoom);
      for (let key in volume_animation_primitives) {
        volume_animation_primitives[key].appearance.material.uniforms.count =
          Math.floor(key / 1000);
      }
    } else if (height >= 50000) {
      if (zoom == 2) return;
      zoom = 2;
      console.log(zoom);
      for (let key in volume_animation_primitives) {
        volume_animation_primitives[key].appearance.material.uniforms.count =
          Math.floor(key / 500);
      }
    } else if (height >= 25000) {
      if (zoom == 3) return;
      zoom = 3;
      console.log(zoom);
      for (let key in volume_animation_primitives) {
        volume_animation_primitives[key].appearance.material.uniforms.count =
          Math.floor(key / 250);
      }
    } else if (height >= 10000) {
      if (zoom == 4) return;
      zoom = 4;
      console.log(zoom);
      for (let key in volume_animation_primitives) {
        volume_animation_primitives[key].appearance.material.uniforms.count =
          Math.floor(key / 100);
      }
    } else if (height >= 5000) {
      if (zoom == 5) return;
      zoom = 5;
      console.log(zoom);
      for (let key in volume_animation_primitives) {
        volume_animation_primitives[key].appearance.material.uniforms.count =
          Math.floor(key / 50);
      }
    } else if (height >= 2500) {
      if (zoom == 6) return;
      zoom = 6;
      console.log(zoom);
      for (let key in volume_animation_primitives) {
        volume_animation_primitives[key].appearance.material.uniforms.count =
          Math.floor(key / 25);
      }
    } else if (height >= 1000) {
      if (zoom == 7) return;
      zoom = 7;
      console.log(zoom);
      for (let key in volume_animation_primitives) {
        volume_animation_primitives[key].appearance.material.uniforms.count =
          Math.floor(key / 10);
      }
    } else if (height >= 500) {
      if (zoom == 8) return;
      zoom = 8;
      console.log(zoom);
      for (let key in volume_animation_primitives) {
        volume_animation_primitives[key].appearance.material.uniforms.count =
          Math.floor(key / 5);
      }
    }
  }, Cesium.ScreenSpaceEventType.WHEEL); // cesium 鼠标滚轮行为
};
// 添加3D Tile
const add3DTileset = (params) => {
  let url = params.url;
  let opacity = params.opacity || 1;
  let setView = params.setView || false;
  if (!url) {
    return;
  }
  const palaceTileset = new Cesium.Cesium3DTileset({
    url: url,
  });
  palaceTileset.readyPromise.then((palaceTileset) => {
    viewer.scene.primitives.add(palaceTileset);
    if (params.position) {
      const position_params = {
        tx: params.position.tx || 0, //模型中心X轴坐标（经度，单位：十进制度）
        ty: params.position.ty || 0, //模型中心Y轴坐标（纬度，单位：十进制度）
        tz: params.position.tz || 0, //模型中心Z轴坐标（高程，单位：米）
        rx: params.position.rx || 0, //X轴（经度）方向旋转角度（单位：度）
        ry: params.position.ry || 0, //Y轴（纬度）方向旋转角度（单位：度）
        rz: params.position.rz || 0, //Z轴（高程）方向旋转角度（单位：度）
      };
      update3dtilesMaxtrix(palaceTileset, position_params);
    }
    // 修改模型的透明度
    palaceTileset.style = new Cesium.Cesium3DTileStyle({
      color: `color('rgba(255,255,255,${opacity})')`,
    });
    if (setView) {
      // 定位模型的位置
      viewer.zoomTo(palaceTileset);
    }
    function update3dtilesMaxtrix(tileset, position_params) {
      //旋转
      var mx = Cesium.Matrix3.fromRotationX(
        Cesium.Math.toRadians(position_params.rx)
      );
      var my = Cesium.Matrix3.fromRotationY(
        Cesium.Math.toRadians(position_params.ry)
      );
      var mz = Cesium.Matrix3.fromRotationZ(
        Cesium.Math.toRadians(position_params.rz)
      );
      var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
      var rotationY = Cesium.Matrix4.fromRotationTranslation(my);
      var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
      //平移
      var position = Cesium.Cartesian3.fromDegrees(
        position_params.tx,
        position_params.ty,
        position_params.tz
      );
      var m = Cesium.Transforms.eastNorthUpToFixedFrame(position);
      //旋转、平移矩阵相乘
      Cesium.Matrix4.multiply(m, rotationX, m);
      Cesium.Matrix4.multiply(m, rotationY, m);
      Cesium.Matrix4.multiply(m, rotationZ, m);
      //赋值给tileset
      tileset._root.transform = m;
    }
  });
  return palaceTileset;
};
// 添加三维管线
const add3DLine = (withOutline, withAnimation, withScale) => {
  const volume = {}; // 管线
  const volume_outline = []; // 管线轮廓
  const volume_animation = {}; // 动画效果
  const volume_scale = {}; // 保证放大后仍能看到管线，其实就是在管线上面贴一个固定px值的线

  // 管线的横截面，radius半径，side_number几边形
  function computeCircle(radius, side_number) {
    const positions = [];
    for (let i = 0; i < side_number; i++) {
      const radians = Cesium.Math.toRadians(i * (360 / side_number)); // 360边形就是一个圆
      positions.push(
        new Cesium.Cartesian2(
          radius * Math.cos(radians),
          radius * Math.sin(radians)
        )
      );
    }
    return positions;
  }

  mapData.features.forEach((feature, index) => {
    const positions = feature.geometry.coordinates[0];
    let p_type = feature.properties.P_TYPE;
    if (p_type === null || p_type === "") {
      p_type = "other";
    }
    if (volume[p_type]) {
      volume[p_type].push(
        new Cesium.GeometryInstance({
          geometry: new Cesium.PolylineVolumeGeometry({
            polylinePositions: Cesium.Cartesian3.fromDegreesArrayHeights(
              handleFromDegreesArrayHeight(positions, heightData[index], 3)
            ),
            shapePositions: computeCircle(0.5, 18),
          }),
        })
      );
    } else {
      volume[p_type] = [
        new Cesium.GeometryInstance({
          geometry: new Cesium.PolylineVolumeGeometry({
            polylinePositions: Cesium.Cartesian3.fromDegreesArrayHeights(
              handleFromDegreesArrayHeight(positions, heightData[index], 3)
            ),
            shapePositions: computeCircle(0.5, 18),
          }),
        }),
      ];
    }
    if (withOutline) {
      volume_outline.push(
        new Cesium.GeometryInstance({
          geometry: new Cesium.PolylineVolumeOutlineGeometry({
            polylinePositions: Cesium.Cartesian3.fromDegreesArrayHeights(
              handleFromDegreesArrayHeight(positions, heightData[index], 3)
            ),
            shapePositions: computeCircle(0.5, 18),
          }),
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(
              new Cesium.Color(255 / 255, 255 / 255, 255 / 255, 1)
            ),
          },
        })
      );
    }
    if (withAnimation) {
      // 每根线的长度不同，因此箭头的数量也不同，根据线的长度计算需要的箭头数
      let count = Math.floor(feature.properties.SHAPE_Length);
      if (volume_animation[count]) {
        volume_animation[count].push(
          new Cesium.GeometryInstance({
            geometry: new Cesium.PolylineGeometry({
              positions: Cesium.Cartesian3.fromDegreesArrayHeights(
                handleFromDegreesArrayHeight(positions, heightData[index], 3.5)
              ),
              width: 10,
            }),
          })
        );
      } else {
        volume_animation[count] = [
          new Cesium.GeometryInstance({
            geometry: new Cesium.PolylineGeometry({
              positions: Cesium.Cartesian3.fromDegreesArrayHeights(
                handleFromDegreesArrayHeight(positions, heightData[index], 3.5)
              ),
              width: 10,
            }),
          }),
        ];
      }
    }
    if (withScale) {
      if (volume_scale[p_type]) {
        volume_scale[p_type].push(
          new Cesium.GeometryInstance({
            geometry: new Cesium.PolylineGeometry({
              positions: Cesium.Cartesian3.fromDegreesArrayHeights(
                handleFromDegreesArrayHeight(positions, heightData[index], 3)
              ),
              width: 5,
            }),
          })
        );
      } else {
        volume_scale[p_type] = [
          new Cesium.GeometryInstance({
            geometry: new Cesium.PolylineGeometry({
              positions: Cesium.Cartesian3.fromDegreesArrayHeights(
                handleFromDegreesArrayHeight(positions, heightData[index], 3)
              ),
              width: 5,
            }),
          }),
        ];
      }
    }
  });

  let volume_color = {
    PF: new Cesium.Color.fromBytes(191, 0, 255, 1),
    PP: new Cesium.Color.fromBytes(0, 255, 255, 1),
    P6: new Cesium.Color.fromBytes(255, 0, 0, 1),
    "P6.2": new Cesium.Color.fromBytes(255, 0, 0, 1),
    P7: new Cesium.Color.fromBytes(255, 165, 0, 1),
    P8: new Cesium.Color.fromBytes(0, 255, 0, 1),
    other: new Cesium.Color.fromBytes(167, 89, 9, 1),
  };

  for (let key in volume) {
    let volume_primitives = new Cesium.Primitive({
      geometryInstances: volume[key],
      releaseGeometryInstances: false,
      appearance: new Cesium.EllipsoidSurfaceAppearance({
        material: new Cesium.Material({
          fabric: {
            uniforms: {
              image: surface_img,
              color: volume_color[key],
            },
            source: `
								uniform vec4 color;

								czm_material czm_getMaterial(czm_materialInput materialInput)
								{
									czm_material material = czm_getDefaultMaterial(materialInput);
									vec2 st = materialInput.st;
									float s = st.s;
									float t = st.t;
									vec4 colorImage = texture(image, vec2(fract(s), t));
									material.diffuse = colorImage.rgb * color.rgb;
									return material;
								}
							`,
          },
        }),
      }),
    });
    viewer.scene.primitives.add(volume_primitives);
  }
  if (withOutline) {
    viewer.scene.primitives.add(
      new Cesium.Primitive({
        geometryInstances: volume_outline,
        appearance: new Cesium.PerInstanceColorAppearance({
          flat: true,
          renderState: {
            lineWidth: 1.0,
          },
        }),
      })
    );
  }
  if (withAnimation) {
    for (let key in volume_animation) {
      volume_animation_primitives[key] = new Cesium.Primitive({
        asynchronous: false,
        geometryInstances: volume_animation[key],
        appearance: new Cesium.PolylineMaterialAppearance({
          material: new Cesium.Material({
            fabric: {
              uniforms: {
                count: Math.floor(key / 1000),
                image: arrow_img,
                color: new Cesium.Color(255 / 255, 255 / 255, 255 / 255, 1),
                speed: 1.0,
              },
              source: `
									uniform vec4 color;
									uniform float count;
		
									czm_material czm_getMaterial(czm_materialInput materialInput)
									{
										czm_material material = czm_getDefaultMaterial(materialInput);
										vec2 st = materialInput.st;

										float s = fract(st.s * count - czm_frameNumber / 60.0 * speed);
										float t = st.t;
										vec4 colorImage = texture(image, vec2(fract(s * 2.0), t));

										float alpha = colorImage.a;
										if(s <= 0.5){
											alpha = 0.0;
										}

										if(count < 0.001) {
											alpha = 0.0;
										}

										material.diffuse = colorImage.rgb;
										material.alpha = alpha;
										return material;
									}
								`,
            },
          }),
        }),
      });
      viewer.scene.primitives.add(volume_animation_primitives[key]);
    }
  }
  if (withScale) {
    for (let key in volume_scale) {
      let volume_scale_primitives = new Cesium.Primitive({
        geometryInstances: volume_scale[key],
        appearance: new Cesium.PolylineMaterialAppearance({
          material: new Cesium.Material({
            fabric: {
              uniforms: {
                image: surface_img,
                color: volume_color[key],
              },
              source: `
								uniform vec4 color;

								czm_material czm_getMaterial(czm_materialInput materialInput)
								{
									czm_material material = czm_getDefaultMaterial(materialInput);
									vec2 st = materialInput.st;
									float s = st.s;
									float t = st.t;
									vec4 colorImage = texture(image, vec2(fract(s), t));
									material.diffuse = colorImage.rgb * color.rgb;
									return material;
								}
							`,
            },
          }),
        }),
      });
      viewer.scene.primitives.add(volume_scale_primitives);
    }
  }
};
const addGLTF = () => {
  // 设置模型方向
  // let headingPitchRoll = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(0), Cesium.Math.toRadians(0), Cesium.Math.toRadians(0));//弧度
  // let orientation = Cesium.Transforms.headingPitchRollQuaternion(position, headingPitchRoll);
  // let model = viewer.entities.add({
  //   // 模型id
  //   id: "model",
  //   // 模型位置
  //   position: position,
  //   // 模型方向
  //   orientation: new Cesium.VelocityOrientationProperty(
  //     computeCirclularFlight()
  //   ),
  //   // 模型资源
  //   model: {
  //     // 模型路径
  //     uri: "./famen.gltf",
  //     scale: 0.2,
  //   },
  // });
  // viewer.zoomTo(model);
  airValveData.features.forEach((feature, index) => {
    let coordinates = feature.geometry.coordinates;
    let position = Cesium.Cartesian3.fromDegrees(
      ...tranformCoordinate(coordinates[0], coordinates[1]),
      airValveHeight[index] + 2.5
    );
    let headingPitchRoll = new Cesium.HeadingPitchRoll(
      Cesium.Math.toRadians(-Number(feature.properties.Angle)),
      Cesium.Math.toRadians(0),
      Cesium.Math.toRadians(0)
    );
    var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
      position,
      headingPitchRoll,
      Cesium.Ellipsoid.WGS84,
      Cesium.Transforms.eastNorthUpToFixedFrame,
      new Cesium.Matrix4()
    );
    // gltf和glb模型都用fromGltf
    viewer.scene.primitives.add(
      Cesium.Model.fromGltf({
        url: "./famen.gltf",
        modelMatrix: modelMatrix,
        scale: 0.2,
        color: new Cesium.Color(1, 0, 0, 1),
      })
    );
  });

  flowctlValveData.features.forEach((feature, index) => {
    let coordinates = feature.geometry.coordinates;
    let position = Cesium.Cartesian3.fromDegrees(
      ...tranformCoordinate(coordinates[0], coordinates[1]),
      flowctlValveHeight[index] + 2.5
    );
    let headingPitchRoll = new Cesium.HeadingPitchRoll(
      Cesium.Math.toRadians(-Number(feature.properties.Angle)),
      Cesium.Math.toRadians(0),
      Cesium.Math.toRadians(0)
    );
    var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
      position,
      headingPitchRoll,
      Cesium.Ellipsoid.WGS84,
      Cesium.Transforms.eastNorthUpToFixedFrame,
      new Cesium.Matrix4()
    );
    // gltf和glb模型都用fromGltf
    viewer.scene.primitives.add(
      Cesium.Model.fromGltf({
        url: "./famen.gltf",
        modelMatrix: modelMatrix,
        scale: 0.2,
        color: new Cesium.Color(0, 0, 1, 1),
      })
    );
  });

  function computeCirclularFlight() {
    const property = new Cesium.SampledPositionProperty();

    let time = Cesium.JulianDate.addSeconds(start, 0, new Cesium.JulianDate());
    let position = Cesium.Cartesian3.fromDegrees(
      114.16761872790354,
      22.274016223656258
    );
    property.addSample(time, position);

    time = Cesium.JulianDate.addSeconds(start, 10, new Cesium.JulianDate());
    position = Cesium.Cartesian3.fromDegrees(
      114.16706393590869,
      22.428101679330513
    );
    property.addSample(time, position);

    return property;
  }
};
// 定位
const setView = (x, y, z) => {
  if (x instanceof Array || y instanceof Array) {
    // 如果x和y是数组，根据x和y计算出定位的矩形范围
    viewer.camera.setView({
      destination: Cesium.Rectangle.fromDegrees(...handleData(x, y)),
      duration: 0,
      complete: () => {},
    });
  } else {
    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(x, y, z),
      duration: 0,
      complete: () => {},
    });
  }

  function handleData(x_arr, y_arr) {
    var xmax = 0;
    var xmin = 180;
    var ymax = 0;
    var ymin = 90;
    x_arr.forEach((x) => {
      xmax = Math.max(xmax, x);
      xmin = Math.min(xmin, x);
    });
    y_arr.forEach((y) => {
      ymax = Math.max(ymax, y);
      ymin = Math.min(ymin, y);
    });
    var shift_x = (xmax - xmin) / 20;
    var shift_y = (ymax - ymin) / 20;
    return [xmin - shift_x, ymin - shift_y, xmax + shift_x, ymax + shift_y];
  }
};
const flyTo = (data) => {
  viewer.flyTo(data);
};
// 获取时间
function getDate() {
  if (dateInterval) clearInterval(dateInterval);
  dateInterval = setInterval(() => {
    date.value = formatDateByProp(new Date(), "yyyy-MM-dd hh:mm:ss");
  }, 1000);
}

onMounted(() => {
  initMap();
  addHandler();
  add3DTileset({
    url: "https://182.160.11.125/3dtiles/tileset.json",
    setView: true,
  });
  pump = add3DTileset({
    url: "https://182.160.11.125/W10484-SWPS-C-N/tileset.json",
    position: {
      tx: 114.18142,
      ty: 22.44429,
      rz: 180,
    },
  });
  pump2 = add3DTileset({
    url: "https://182.160.11.125/W20229-MWBRWPS-M-B-000-NN/tileset.json",
    position: {
      tx: 114.1314395,
      ty: 22.5404925,
      rz: 182.5,
    },
  });
  add3DLine(false, false, true);
  addGLTF();
  // setView(114.18142, 22.44429, 100000);
  // getDate();
});
</script>

<style lang="scss" scoped>
#cesium-container {
  position: absolute;
  top: 0;
  left: 0;
  // width: calc(100% - 400px);
  width: 100%;
  height: 100%;
}
.right-side {
  position: absolute;
  top: 0;
  right: 0;
  width: 400px;
  height: 100%;
  padding: 10px;
  background-color: #f2f2f2;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .component {
    display: flex;
    justify-content: space-between;
    .component-item {
      color: #fff;
      background-color: rgb(64, 158, 255);
      display: flex;
      justify-content: center;
      align-items: center;
      height: 25px;
      width: 180px;
    }
  }
  .content-item {
    height: 30%;
    background-color: #fcfcfc;
    padding: 10px 20px;
    .title {
      display: flex;
      align-items: center;
      .info {
        color: #555555;
        font-weight: 600;
        font-size: 14px;
      }
      .select {
        margin-left: 10px;
      }
    }
  }
}
.left-side {
  position: absolute;
  top: 65px;
  left: 20px;
  width: 300px;
  height: 85%;
  padding: 40px 20px 10px 10px;
  background-color: #ffffff;
  border: 2px solid #797979;
  z-index: 10;
  overflow-y: auto;

  .tab {
    top: 10px;
    left: 10px;

    .tab-item {
      font-size: 12px;
    }
  }

  .content-item {
    background: #f8f8f8;
    padding: 5px;
    margin-top: 10px;

    .title {
      display: flex;
      align-items: center;
      .info {
        color: #555555;
        font-weight: 600;
        font-size: 12px;
      }
    }

    .table {
      font-size: 12px;
      .table-header {
        display: flex;
        margin-top: 5px;

        & > div {
          padding: 0 3px;

          &:nth-child(1) {
            width: 40%;
          }

          &:nth-child(2) {
            width: 40%;
          }

          &:nth-child(3) {
            width: 20%;
          }
        }
      }

      .table-body {
        display: flex;
        background: #c1e8fb;
        margin-top: 5px;

        & > div {
          padding: 0 3px;
          display: flex;
          align-items: center;

          &:nth-child(1) {
            width: 40%;
          }

          &:nth-child(2) {
            width: 40%;
            color: #409eff;
            font-weight: 600;
          }

          &:nth-child(3) {
            width: 20%;
            color: #409eff;
            font-weight: 600;
          }
        }
      }
    }
  }
}

.arrow {
  .arrow-item {
    color: #fff;
    background-color: rgb(64, 158, 255);
    height: 60px;
    width: 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    cursor: pointer;
    position: absolute;
    z-index: 20;
  }
  .arrow-left {
    top: calc(42.5% + 65px);
    left: 320px;
    transform: translateY(-50%) translateX(-80%);
  }
  .arrow-right {
    top: calc(42.5% + 65px);
    left: 20px;
    transform: translateY(-50%);
  }
}

.tab {
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 0;
  margin: 0;
  z-index: 10;
  display: flex;

  .tab-item {
    color: #fff;
    background-color: #ababab;
    padding: 5px;
    border-radius: 3px;
    cursor: pointer;
    margin-right: 5px;
  }

  .active {
    background-color: #409eff;
  }
}

.pump-btn {
  position: absolute;
  top: 5px;
  right: 50px;
  padding: 10px;
  background: #303336;
  color: #fff;
  border: 1px solid #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.legend {
  position: fixed;
  right: 10px;
  bottom: 10px;
  background-color: #ccc;
  padding: 15px;
  border-radius: 10px;

  .legend-item {
    display: flex;
    align-items: center;

    .legend-icon {
      height: 10px;
      width: 10px;
      margin-right: 10px;
    }
  }
}
</style>
